//
//  ZYViewController.m
//  DaDaLiCai
//
//  Created by admin on 15/11/10.
//  Copyright © 2015年 Mikeshihua. All rights reserved.
//
#import "ServicesCell.h"
#import "ZYViewController.h"
#import "ServiceModel.h"
#import "ServiceDetailViewController.h"

@interface ZYViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic,strong)UICollectionView * mainCollectionView;
@property (nonatomic,strong)NSMutableArray     * dataSourceArray;

@property (nonatomic,strong)UIView *noDataView;
@property (nonatomic,strong)UIView *noNet;

@property (nonatomic, assign)int idx;
@property (nonatomic,assign) int n;
@end

@implementation ZYViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self createTheNavigationBar];
    [self createTheUi];
}
#pragma mark --------------表的刷新与加载更多
-(void)refreshTheTableView
{
    _idx = 0;
    _n = 0;
    
    [self getHttpData];
}
- (void)AddtoTheProjectTableView
{
    [self getHttpData];
}
-(void)getHttpData
{
    self.noDataView.hidden = TRUE;
    self.noNet.hidden = TRUE;
    if (!_dataSourceArray)
    {
        _dataSourceArray = [NSMutableArray array];
    }
    _n++;
    [AppGlobalClass PostDataWithNSstring:GETGROUPLIST withDictionary:@{@"page.size":[NSNumber numberWithInt:10],@"page.pn":[NSNumber numberWithInt:_idx + 1]} success:^(NSDictionary *dictionary) {
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            [self.mainCollectionView.header endRefreshing];
            [self.mainCollectionView.footer setState:MJRefreshStateIdle];
            [self.mainCollectionView.footer endRefreshing];
            
            if(_idx == 0)
            {
                [_dataSourceArray removeAllObjects];
            }
            
            NSArray *dataArray = [dictionary objectForKey:@"responseData"];
            NSDictionary *dataDict = [dataArray firstObject];
            
            if([[dataDict objectForKey:@"pages"] intValue] > _idx)
            {
                
                NSMutableArray *listArray = [[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"];
                
                for (NSDictionary * dataDict in listArray)
                {
                    ServiceModel * model = [[ServiceModel alloc]init];
                    [model setValuesForKeysWithDictionary:dataDict];
                    [_dataSourceArray addObject:model];
                }
                _idx++;
                
                [self.mainCollectionView reloadData];
                
                if(_dataSourceArray.count < 10)
                {
                    [self.mainCollectionView.footer endRefreshingWithNoMoreData];
                }
                else
                {
                    if (_n<2) {
                        
                        self.mainCollectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(AddtoTheProjectTableView)];
                        
                    }
                    
                }
            }
            else
            {
                if (self.dataSourceArray.count==0) {
                    
                    //                    无数据
                    self.noDataView.hidden = FALSE;
                    
                }
                
                [self.mainCollectionView.footer endRefreshingWithNoMoreData];
            }
            
        }else{
            //没有真确返回
            [self.dataSourceArray removeAllObjects];
            [_mainCollectionView reloadData];
            _noDataView.hidden = FALSE;
            
            [self.mainCollectionView.header endRefreshing];
            [self.mainCollectionView.footer setState:MJRefreshStateIdle];
            [self.mainCollectionView.footer endRefreshing];
        }

    } failure:^(NSError *error) {
        _noDataView.hidden = FALSE;
        [_dataSourceArray removeAllObjects];
        [_mainCollectionView reloadData];
        [self.mainCollectionView.header endRefreshing];
        [self.mainCollectionView.footer setState:MJRefreshStateIdle];
        [self.mainCollectionView.footer endRefreshing];
    } networkerror:^(NSString *networkerror) {
        _noNet.hidden = FALSE;
        [_dataSourceArray removeAllObjects];
        [_mainCollectionView reloadData];
        [self.mainCollectionView.header endRefreshing];
        [self.mainCollectionView.footer setState:MJRefreshStateIdle];
        [self.mainCollectionView.footer endRefreshing];
    }];

}
-(void)createTheNavigationBar
{
    TopView *topView = [[TopView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_HEIGHT, 64.0f)];
    topView.backgroundColor = [UIColor hexStringToColor:COLOR_VALUE];
    [topView setTitile:@"服务"];
    [self.view addSubview:topView];
}
-(void)createTheUi
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _mainCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64-49) collectionViewLayout:layout];
    _mainCollectionView.backgroundColor = RGBA(229, 230, 231, 1);
    _mainCollectionView.dataSource = self;
    _mainCollectionView.delegate = self;
    [_mainCollectionView registerClass:[ServicesCell class] forCellWithReuseIdentifier:@"cell"];
    _mainCollectionView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTheTableView)];
    [self.view addSubview:_mainCollectionView];
    [self.mainCollectionView addSubview:self.noDataView];
    [self.mainCollectionView addSubview:self.noNet];
    [_mainCollectionView.header beginRefreshing];
    
}
#pragma mark-----------dataSource和delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataSourceArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ServicesCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (!cell)
    {
        cell = [[ServicesCell alloc]initWithFrame:CGRectZero];
    }
    if (_dataSourceArray.count >0)
    {
        ServiceModel * model = _dataSourceArray[indexPath.row];
        cell.serviceImageView.contentMode = UIViewContentModeCenter;
        [cell.serviceImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMAGE_URL_TEST,model.imageUrl]] placeholderImage:[UIImage imageNamed:@"img_default"] options:SDWebImageRetryFailed completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            cell.serviceImageView.clipsToBounds = TRUE;
            cell.serviceImageView.contentMode = UIViewContentModeScaleAspectFill;
        }];
        cell.serviceLable.text = model.title;
    }
    return cell;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 8;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10.0;
}

//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(16, 16, 16, 16);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((SCREEN_WIDTH-40)/2.0, (SCREEN_WIDTH-40)/2.0);
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ServiceModel * model = _dataSourceArray[indexPath.row];
    ServiceDetailViewController * vc = [[ServiceDetailViewController alloc]initWithGroupId:[NSString stringWithFormat:@"%@",model.groupId]];
    [self.navigationController pushViewController:vc animated:TRUE];
}

//没网提示
#pragma mark - 无网提示
-(UIView *)noNet
{
    if (!_noNet) {
        _noNet = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
        _noNet.center = CGPointMake(_mainCollectionView.center.x, _mainCollectionView.center.y - 64 - 32);
        _noNet.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 200, 200);
        [button setImage:[UIImage imageNamed:@"img_nonetwork"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 40, 200, 44)];
        label.text = @"网络不通\n点击重新搜索";
        label.font = [UIFont systemFontOfSize:15.0f];
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        label.textColor = [UIColor colorWithWhite:0.000 alpha:0.540];
        [_noNet addSubview:label];
        [_noNet addSubview:button];
    }
    return _noNet;
}

-(UIView *)noDataView{
    if (!_noDataView) {
        
        _noDataView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
        _noDataView.center =CGPointMake(_mainCollectionView.center.x, _mainCollectionView.center.y - 64 - 32);
        _noDataView.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 200, 200);
        [button setImage:[UIImage imageNamed:@"img_nodata"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 40, 200, 44)];
        label.text = @"暂无数据\n点击重新搜索";
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        label.font = [UIFont systemFontOfSize:14.0f];
        
        label.textColor = [UIColor colorWithWhite:0.000 alpha:0.540];
        [_noDataView addSubview:label];
        [_noDataView addSubview:button];
    }
    
    return _noDataView;
}
- (void)noResultButtonAction:(id)sender
{
    [self.mainCollectionView.header beginRefreshing];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
